<template>
  <div>
    <!-- 查询条件 -->
    <el-form :inline="true" :model="query" class="query-form" @submit.prevent>
      <el-form-item label="出库单编号">
        <el-input v-model="query.outCode" placeholder="请输入出库单编号" clearable />
      </el-form-item>
      <el-form-item label="销售订单编号">
        <el-input v-model="query.salesCode" placeholder="请输入销售订单编号" clearable />
      </el-form-item>
      <el-form-item label="客户名称">
        <el-input v-model="query.customerName" placeholder="请输入客户名称" clearable />
      </el-form-item>
      <el-form-item label="出库日期">
        <el-date-picker v-model="query.outTime" type="date" placeholder="请选择出库日期" clearable />
      </el-form-item>
      <el-form-item label="单据状态" class="status-form-item">
        <el-select v-model="query.status" placeholder="请选择单据状态" clearable class="status-select">
          <el-option label="草稿" value="0" />
          <el-option label="待拣货" value="1" />
          <el-option label="已取消" value="2" />
          <el-option label="已完成" value="3" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <div class="table-operations">
      <el-button type="primary" @click="handleAdd">新增</el-button>
      <el-button type="danger" @click="handleBatchDelete" :disabled="!hasDeleteableRows">批量删除</el-button>
    </div>

    <!-- 数据表格 -->
    <el-table 
      :data="tableData" 
      style="width: 100%; margin-top: 16px;"
      @selection-change="handleSelectionChange"
      border
      fit
      stripe
      highlight-current-row
      :header-cell-style="{ background: '#f5f7fa' }"
    >
      <el-table-column type="selection" width="45" fixed="left" />
      <el-table-column prop="outCode" label="出库单编号" min-width="120" show-overflow-tooltip fixed="left" />
      <el-table-column prop="outName" label="出库名称" min-width="120" show-overflow-tooltip />
      
      <el-table-column prop="shipmentCode" label="发货编号" min-width="120" show-overflow-tooltip />
      <el-table-column prop="salesCode" label="销售编号" min-width="120" show-overflow-tooltip />
      <el-table-column prop="customerCode" label="客户编码" min-width="120" show-overflow-tooltip />
      <el-table-column prop="customerName" label="客户名称" min-width="150" show-overflow-tooltip />
      <el-table-column prop="people" label="收货人" min-width="100" show-overflow-tooltip />
      <el-table-column prop="phone" label="联系方式" min-width="120" show-overflow-tooltip />
      <el-table-column prop="address" label="收货地址" min-width="200" show-overflow-tooltip />
      <el-table-column label="出库日期" min-width="110" align="center">
        <template #default="scope">
          {{ formatDate(scope.row.outTime) }}
        </template>
      </el-table-column>
      <el-table-column label="单据状态" min-width="90" align="center">
        <template #default="scope">
          <el-tag :type="getStatusTagType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="200" fixed="right">
        <template #default="scope">
          <div class="operation-group">
            <!-- 草稿状态 -->
            <template v-if="Number(scope.row.status) === 0">
              <el-button size="small" @click="handleEdit(scope.row)">修改</el-button>
              <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
              <el-button size="small" type="success" @click="handleUpdateStatus(scope.row, 1)">执行拣货</el-button>
            </template>
            
            <!-- 待拣货状态 -->
            <template v-else-if="Number(scope.row.status) === 1">
              <el-button size="small" type="primary" @click="handleUpdateStatus(scope.row, 3)">完成出库</el-button>
              <el-button size="small" type="warning" @click="handleUpdateStatus(scope.row, 2)">取消</el-button>
            </template>
            
            <!-- 非已取消和已完成状态 -->
            <template v-else-if="Number(scope.row.status) !== 2 && Number(scope.row.status) !== 3">
              <el-button size="small" type="warning" @click="handleUpdateStatus(scope.row, 2)">取消</el-button>
            </template>
            
            <!-- 已取消或已完成状态 -->
            <template v-else>
              <span class="no-operation">无可用操作</span>
            </template>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      style="margin-top: 16px; text-align: right"
      background
      layout="total, prev, pager, next, sizes, jumper"
      :total="total"
      :page-size="query.pageSize"
      :current-page="query.pageIndex"
      @current-change="handlePageChange"
      @size-change="handleSizeChange"
      :page-sizes="[5, 10, 20, 50]"
    />

    <!-- 添加/编辑对话框 -->
    <el-dialog 
      :title="dialogStatus === 'add' ? '新增出库单' : '编辑出库单'" 
      v-model="dialogVisible" 
      width="650px" 
      :close-on-click-modal="false"
      class="sales-out-dialog"
    >
      <el-form 
        ref="formRef" 
        :model="form" 
        :rules="formRules" 
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="出库单编号" prop="outCode">
              <el-input v-model="form.outCode" placeholder="请输入出库单编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出库名称" prop="outName">
              <el-input v-model="form.outName" placeholder="请输入出库名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="发货编号" prop="shipmentCode">
              <el-input v-model="form.shipmentCode" placeholder="请输入发货编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="销售编号" prop="salesCode">
              <el-input v-model="form.salesCode" placeholder="请输入销售编号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="客户编码" prop="customerCode">
              <div class="search-input">
                <el-input 
                  v-model="form.customerCode" 
                  placeholder="请选择客户" 
                  readonly 
                  @click="openCustomerSelector"
                />
                <div class="search-icon" @click="openCustomerSelector">
                  <i class="el-icon-search"></i>
                </div>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户名称" prop="customerName">
              <el-input v-model="form.customerName" placeholder="客户名称" readonly disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="收货人" prop="people">
              <el-input v-model="form.people" placeholder="收货人信息" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系方式" prop="phone">
              <el-input v-model="form.phone" placeholder="联系方式" readonly disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="出库日期" prop="outTime">
              <el-date-picker 
                v-model="form.outTime" 
                type="datetime" 
                placeholder="请选择出库日期"
                style="width: 100%;"
                value-format="YYYY-MM-DD HH:mm:ss" 
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单据状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择单据状态" style="width: 100%;">
                <el-option label="草稿" :value="0" />
                <el-option label="待拣货" :value="1" />
                <el-option label="已取消" :value="2" />
                <el-option label="已完成" :value="3" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="收货地址" prop="address">
          <el-input 
            v-model="form.address" 
            type="textarea" 
            placeholder="请输入收货地址"
            :rows="3" 
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 客户选择对话框 -->
    <el-dialog
      title="客户选择" 
      v-model="customerSelectorVisible" 
      width="800px"
      class="customer-selector-dialog"
      append-to-body
      destroy-on-close
    >
      <div class="customer-search">
        <el-form :inline="true" @submit.prevent>
          <el-form-item label="客户编码">
            <el-input v-model="customerQuery.code" placeholder="请输入客户编码" clearable />
          </el-form-item>
          <el-form-item label="客户名称">
            <el-input v-model="customerQuery.name" placeholder="请输入客户名称" clearable />
          </el-form-item>
          <el-form-item label="客户简称">
            <el-input v-model="customerQuery.abbreviation" placeholder="请输入客户简称" clearable />
          </el-form-item>
          <el-form-item label="客户类型">
            <el-select v-model="customerQuery.type" placeholder="请选择客户类型" clearable style="width: 150px;">
              <el-option label="企业客户" value="企业客户" />
              <el-option label="个体工商户" value="个体工商户" />
              <el-option label="其他" value="其他" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="customerQuery.isEnable" placeholder="选择状态" clearable style="width: 100px;">
              <el-option :label="'启用'" :value="1" />
              <el-option :label="'禁用'" :value="0" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchCustomers" :loading="customerLoading">搜索</el-button>
            <el-button @click="resetCustomerQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-table
        :data="customerList"
        height="350"
        border
        highlight-current-row
        v-loading="customerLoading"
        stripe
        :header-cell-style="{ background: '#f5f7fa' }"
      >
        <el-table-column prop="custCode" label="客户编码" width="100" />
        <el-table-column prop="custName" label="客户名称" width="160" />
        <el-table-column prop="custAbbreviation" label="客户简称" width="120" />
        <el-table-column prop="custType" label="客户类型" width="100" />
        <el-table-column prop="conPerson" label="联系人" width="100" />
        <el-table-column prop="conPersonPhone" label="联系人电话" width="120" />
        <el-table-column prop="custPhone" label="客户电话" width="120" />
        <el-table-column prop="isEnable" label="状态" min-width="80" show-overflow-tooltip>
          <template #default="scope">
            <el-tag :type="scope.row.isEnable === 1 ? 'success' : 'danger'">
              {{ scope.row.isEnable === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" fixed="right">
          <template #default="scope">
            <el-button 
              size="small" 
              type="primary" 
              @click="handleSelectCustomer(scope.row)"
            >选择</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          background
          layout="total, prev, pager, next, sizes"
          :total="customerTotal"
          :page-size="customerQuery.pageSize"
          :current-page="customerQuery.pageIndex"
          @current-change="handleCustomerPageChange"
          @size-change="handleCustomerSizeChange"
          :page-sizes="[5, 10, 20, 50]"
        />
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, nextTick } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'

interface SalesOutRow {
  id?: number
  outCode: string
  outName: string
  shipmentCode: string
  salesCode: string
  customerCode: string
  customerName: string
  people: string
  phone: string
  address: string
  outTime: string
  status: number | string
  [key: string]: any
}

interface CustomerRow {
  custId?: number
  custCode: string
  custName: string
  custAbbreviation?: string
  custType?: string
  custPhone: string
  conPerson: string
  conPersonPhone: string
  custAddress: string
  isEnable?: number
  [key: string]: any
}

const tableData = ref<SalesOutRow[]>([])
const total = ref(0)
const selectedRows = ref<SalesOutRow[]>([])
const dialogVisible = ref(false)
const dialogStatus = ref<'add' | 'edit'>('add')
const formRef = ref()

// 计算属性：是否有可删除的行（草稿状态）
const hasDeleteableRows = computed(() => {
  return selectedRows.value.length > 0 && selectedRows.value.some(row => Number(row.status) === 0)
})

// 客户选择相关
const customerSelectorVisible = ref(false)
const customerList = ref<CustomerRow[]>([])
const customerTotal = ref(0)
const customerLoading = ref(false)
const customerQuery = reactive({
  code: '',
  name: '',
  abbreviation: '',
  type: '',
  isEnable: '',
  pageIndex: 1,
  pageSize: 10
})

const query = reactive<{ [key: string]: any }>(
  {
    outCode: '',
    salesCode: '',
    customerName: '',
    outTime: '',
    status: '',
    pageIndex: 1,
    pageSize: 10
  }
)

// 初始表单数据
const defaultForm: SalesOutRow = {
  outCode: '',
  outName: '',
  shipmentCode: '',
  salesCode: '',
  customerCode: '',
  customerName: '',
  people: '',
  phone: '',
  address: '',
  outTime: '',
  status: 0
}

const form = reactive<SalesOutRow>({...defaultForm})

// 表单验证规则
const formRules = {
  outCode: [{ required: true, message: '请输入出库单编号', trigger: 'blur' }],
  salesCode: [{ required: true, message: '请输入销售编号', trigger: 'blur' }],
  customerCode: [{ required: true, message: '请选择客户', trigger: 'change' }],
  customerName: [{ required: true, message: '客户名称不能为空', trigger: 'change' }],
  people: [{ required: true, message: '请输入收货人', trigger: 'blur' }]
  // outTime已移除必填验证
}

// 打开客户选择器
function openCustomerSelector() {
  customerSelectorVisible.value = true
  resetCustomerQuery()
  searchCustomers()
}

// 搜索客户
function searchCustomers() {
  customerLoading.value = true;
  
  // 构建参数对象，确保非空值才会被包含
  const params: Record<string, any> = {
    CustCode: customerQuery.code || '',
    CustName: customerQuery.name || '',
    CustAbbreviation: customerQuery.abbreviation || ''
  };
  
  // 单独处理客户类型 - 确保类型参数被正确传递
  if (customerQuery.type) {
    params.CustType = customerQuery.type;
  }
  
  // 单独处理启用状态 - 保证0值可以被正确传递
  if (customerQuery.isEnable !== '') {
    params.IsEnable = customerQuery.isEnable;
  }
  
  // 添加分页信息
  params.PageIndex = customerQuery.pageIndex || 1;
  params.PageSize = customerQuery.pageSize || 10;
  
  // 调试日志 - 帮助排查问题
  console.log('发送客户查询参数:', params);
  
  // 使用WarehouseManagement API获取客户数据
  axios.get('/api/WarehouseManagement/GetCustomerList', { params })
    .then(res => {
      console.log('客户数据返回:', res.data);
      
      if (res.data && res.data.rows && Array.isArray(res.data.rows)) {
        customerList.value = res.data.rows;
        customerTotal.value = res.data.total || res.data.rows.length;
      } else if (res.data && Array.isArray(res.data)) {
        customerList.value = res.data;
        customerTotal.value = res.data.length;
      } else if (res.data && res.data.data && Array.isArray(res.data.data)) {
        // 处理可能的嵌套数据格式
        customerList.value = res.data.data;
        customerTotal.value = res.data.total || res.data.data.length;
      } else {
        customerList.value = [];
        customerTotal.value = 0;
        ElMessage.warning('未找到客户数据');
      }
    })
    .catch(err => {
      console.error('获取客户数据失败:', err);
      ElMessage.error('获取客户数据失败');
      customerList.value = [];
      customerTotal.value = 0;
    })
    .finally(() => {
      customerLoading.value = false;
    });
}

// 重置客户查询条件
function resetCustomerQuery() {
  customerQuery.code = ''
  customerQuery.name = ''
  customerQuery.abbreviation = ''
  customerQuery.type = ''
  customerQuery.isEnable = ''
  customerQuery.pageIndex = 1
  searchCustomers()
}

// 客户选择翻页
function handleCustomerPageChange(page: number) {
  customerQuery.pageIndex = page
  searchCustomers()
}

// 客户选择页大小变化
function handleCustomerSizeChange(size: number) {
  customerQuery.pageSize = size
  customerQuery.pageIndex = 1
  searchCustomers()
}

// 选择客户
function handleSelectCustomer(row: CustomerRow) {
  form.customerCode = row.custCode
  form.customerName = row.custName
  form.people = row.conPerson || ''
  form.phone = row.conPersonPhone || row.custPhone || ''
  form.address = row.custAddress || ''
  
  customerSelectorVisible.value = false
  ElMessage.success('已选择客户: ' + row.custName)
}

// 格式化日期，只显示年月日
function formatDate(dateStr: string): string {
  if (!dateStr) return '';
  
  // 尝试转换为日期对象
  const date = new Date(dateStr);
  if (isNaN(date.getTime())) {
    // 如果无法转换，直接返回原始字符串或者截取前10位
    return dateStr.length > 10 ? dateStr.substring(0, 10) : dateStr;
  }
  
  // 格式化为YYYY-MM-DD
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
}

// 搜索
function handleSearch() {
  query.pageIndex = 1
  
  // 保存日期查询值，但不发送到后端
  const searchDate = query.outTime;
  const tempOutTime = query.outTime;
  query.outTime = ''; // 清空，不发送到后端
  
  // 检查所有查询参数并输出日志
  console.log('查询参数:', query)
  
  fetchData().then(() => {
    // 获取数据后在前端过滤日期
    if (searchDate) {
      const dateStr = formatDateToString(searchDate);
      console.log('前端过滤日期:', dateStr);
      
      // 前端过滤日期
      tableData.value = tableData.value.filter(item => {
        if (!item.outTime) return false;
        return formatDate(item.outTime).includes(dateStr);
      });
    }
    
    // 恢复日期值，用于UI显示
    query.outTime = tempOutTime;
  });
}

// 日期格式转换为字符串，用于前端过滤
function formatDateToString(date: any): string {
  if (!date) return '';
  
  if (date instanceof Date) {
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
  }
  
  // 如果已经是字符串，就返回前10位 (YYYY-MM-DD)
  if (typeof date === 'string' && date.length >= 10) {
    return date.substring(0, 10);
  }
  
  return '';
}

// 获取数据列表
function fetchData() {
  // 构造参数，去除空值
  const params: any = {}
  Object.keys(query).forEach(key => {
    if (query[key] !== '' && query[key] !== null && query[key] !== undefined) {
      params[key] = query[key]
    }
  })
  
  console.log('发送请求参数:', params)
  
  return axios.get('/api/WarehouseManagement/GetSalesOutPages', { params }).then(res => {
    console.log('API返回数据:', res)
    if (res.data && Array.isArray(res.data.rows)) {
      tableData.value = res.data.rows
      total.value = res.data.total || res.data.rows.length
    } else if (Array.isArray(res.data)) {
      tableData.value = res.data
      total.value = res.data.length
    } else {
      tableData.value = []
      total.value = 0
    }
    
    return res;
  }).catch(err => {
    console.error('获取数据失败:', err)
    ElMessage.error('获取数据失败')
    return Promise.reject(err);
  })
}

// 重置
function handleReset() {
  query.outCode = ''
  query.salesCode = ''
  query.customerName = ''
  query.outTime = ''
  query.status = ''
  query.pageIndex = 1
  fetchData()
}

// 分页处理
function handlePageChange(page: number) {
  query.pageIndex = page
  fetchData()
}

function handleSizeChange(size: number) {
  query.pageSize = size
  query.pageIndex = 1
  fetchData()
}

// 表格选择
function handleSelectionChange(selection: SalesOutRow[]) {
  selectedRows.value = selection
}

// 新增
function handleAdd() {
  dialogStatus.value = 'add'
  
  // 更彻底地重置表单 - 使用一个全新的空对象彻底替换
  const emptyForm: SalesOutRow = {
    id: undefined,
    outCode: '',
    outName: '',
    shipmentCode: '',
    salesCode: '',
    customerCode: '',
    customerName: '',
    people: '',
    phone: '',
    address: '',
    outTime: '',
    status: 0
  };
  
  // 使用Object.assign彻底重置表单
  Object.assign(form, emptyForm);
  
  dialogVisible.value = true
  
  // 重置验证
  nextTick(() => {
    formRef.value?.resetFields()
  })
}

// 编辑
function handleEdit(row: SalesOutRow) {
  dialogStatus.value = 'edit'
  // 填充表单数据
  Object.assign(form, JSON.parse(JSON.stringify(row)))
  dialogVisible.value = true
}

// 删除
function handleDelete(row: SalesOutRow) {
  // 检查状态是否为草稿
  if (Number(row.status) !== 0) {
    ElMessage.warning('只能删除草稿状态的记录')
    return
  }

  ElMessageBox.confirm(`确认要删除出库单 ${row.outCode} 吗?`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 调用删除API，发送单个ID的数组
      const response = await axios.post('/api/WarehouseManagement/BatchDeleteSalesOut', [row.id])
      
      if (response.data && (response.data.status === true || response.data.success === true)) {
        ElMessage.success('删除成功')
        fetchData() // 刷新列表
      } else {
        ElMessage.error(response.data?.message || response.data?.msg || '删除失败')
      }
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败，请稍后重试')
    }
  }).catch(() => {})
}

// 批量删除
function handleBatchDelete() {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的记录')
    return
  }

  // 检查是否所有选中的行都是草稿状态
  const nonDraftItems = selectedRows.value.filter(row => Number(row.status) !== 0)
  if (nonDraftItems.length > 0) {
    ElMessage.warning('只能删除草稿状态的记录，请重新选择')
    return
  }

  // 获取所有选中行的ID
  const selectedIds = selectedRows.value.map(row => row.id)

  ElMessageBox.confirm(`确认要删除已选择的 ${selectedRows.value.length} 条记录吗?`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 调用批量删除API
      const response = await axios.post('/api/WarehouseManagement/BatchDeleteSalesOut', selectedIds)
      
      if (response.data && (response.data.status === true || response.data.success === true)) {
        ElMessage.success(`成功删除 ${selectedRows.value.length} 条记录`)
        fetchData() // 刷新列表
      } else {
        ElMessage.error(response.data?.message || response.data?.msg || '删除失败')
      }
    } catch (error) {
      console.error('批量删除失败:', error)
      ElMessage.error('删除失败，请稍后重试')
    }
  }).catch(() => {})
}

// 更新销售出库单状态
function handleUpdateStatus(row: SalesOutRow, newStatus: number) {
  // 根据不同状态显示不同的确认信息
  let confirmTitle = '确认更新状态';
  let confirmMessage = '';
  let successMessage = '';
  
  switch(newStatus) {
    case 1:
      confirmTitle = '执行拣货';
      confirmMessage = '确认将该单据状态更新为"待拣货"吗?';
      successMessage = '已成功更新为待拣货状态';
      break;
    case 2:
      confirmTitle = '取消单据';
      confirmMessage = '确认取消该单据吗?';
      successMessage = '单据已取消';
      break;
    case 3:
      confirmTitle = '完成出库';
      confirmMessage = '确认将该单据状态更新为"已完成"吗?';
      successMessage = '单据已完成';
      break;
  }
  
  ElMessageBox.confirm(confirmMessage, confirmTitle, {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 调用API更新状态 - 使用URL参数方式
      const response = await axios.post(`/api/WarehouseManagement/UpdateSalesOutStatus?id=${row.id}&status=${newStatus}`);
      
      console.log('状态更新返回:', response.data);
      
      if (response.data === true || (response.data && response.data.success === true)) {
        ElMessage.success(successMessage);
        fetchData(); // 刷新列表
      } else {
        ElMessage.error(response.data?.message || response.data?.msg || '状态更新失败');
      }
    } catch (error) {
      console.error('状态更新失败:', error);
      ElMessage.error('状态更新失败，请稍后重试');
    }
  }).catch(() => {
    // 用户取消操作，不做任何事
  });
}

// 提交表单
function submitForm() {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      if (dialogStatus.value === 'add') {
        axios.post('/api/WarehouseManagement/AddSalesOut', form)
          .then(res => {
            if (res.data === true) {
              ElMessage.success('添加成功')
              dialogVisible.value = false
              fetchData() // 刷新列表
            } else {
              ElMessage.error('添加失败')
            }
          })
          .catch(err => {
            console.error('添加失败:', err)
            ElMessage.error('添加失败')
          })
      } else {
        axios.post('/api/WarehouseManagement/UpdateSalesOut', form)
          .then(res => {
            if (res.data === true) {
              ElMessage.success('更新成功')
              dialogVisible.value = false
              fetchData() // 刷新列表
            } else {
              ElMessage.error('更新失败')
            }
          })
          .catch(err => {
            console.error('更新失败:', err)
            ElMessage.error('更新失败')
          })
      }
    }
  })
}

// 获取状态文字描述
function getStatusText(status: string | number): string {
  const statusMap: Record<string, string> = {
    '0': '草稿',
    '1': '待拣货',
    '2': '已取消',
    '3': '已完成'
  }
  
  return statusMap[status.toString()] || '未知状态'
}

// 获取状态标签类型
function getStatusTagType(status: string | number): string {
  const typeMap: Record<string, string> = {
    '0': 'info',
    '1': 'warning',
    '2': 'danger',
    '3': 'success'
  }
  
  return typeMap[status.toString()] || 'info'
}

onMounted(() => {
  fetchData()
  // 初始化时预加载客户数据
  searchCustomers()
})
</script>

<style scoped>
.query-form {
  margin-bottom: 16px;
  margin-top: 20px; /* 增加上方间距 */
  padding-top: 10px; /* 增加内边距 */
}

.table-operations {
  margin-bottom: 16px;
  margin-top: 16px; /* 增加按钮区域上方间距 */
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

/* 增加单据状态下拉框宽度 */
.status-select {
  min-width: 160px;
  width: 160px;
}

/* 确保表单项间距适当 */
.status-form-item {
  margin-right: 10px;
  min-width: 180px;
}

/* 表格样式优化 */
:deep(.el-table) {
  border-radius: 4px;
  overflow: hidden;
}

:deep(.el-table th) {
  font-weight: bold;
  color: #2c3e50;
  height: 48px;
}

:deep(.el-table--border th:first-child) {
  border-left: none;
}

:deep(.el-table--border th:last-child) {
  border-right: none;
}

:deep(.el-table__row) {
  height: 50px;
}

:deep(.el-table__row:hover td) {
  background-color: #ecf5ff !important;
}

/* 操作按钮组样式 */
.operation-group {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  justify-content: center;
}

.operation-group .el-button {
  margin-left: 0;
  flex: 0 0 auto;
  padding: 6px 10px;
  font-size: 12px;
  height: 30px;
  line-height: 1;
}

.no-operation {
  color: #909399;
  font-size: 13px;
}

/* 客户编码搜索样式 */
.search-input {
  position: relative;
  width: 100%;
}

.search-input .el-input {
  width: 100%;
}

.search-input .el-input :deep(input) {
  padding-right: 30px; /* 为搜索图标留出空间 */
  cursor: pointer;
}

.search-icon {
  position: absolute;
  right: 8px;
  top: 0;
  height: 100%;
  display: flex;
  align-items: center;
  color: #909399;
  cursor: pointer;
  font-size: 16px;
}

.search-icon:hover {
  color: #409EFF;
}

/* 移除之前的输入框按钮样式 */
.input-with-button {
  display: none;
}

/* 客户选择对话框样式 */
.customer-search {
  margin-bottom: 15px;
}

.pagination-container {
  margin-top: 15px;
  text-align: right;
}

/* 全局样式，需要添加到全局CSS或使用:deep */
:deep(.sales-out-dialog .el-dialog__body) {
  padding: 20px 30px !important;
}

:deep(.customer-selector-dialog .el-dialog__body) {
  padding: 20px !important;
}
</style>